package com.dymall.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dymall.common.domain.dto.AddressDTO;
import com.dymall.common.exception.BadRequestException;
import com.dymall.common.util.BeanUtils;
import com.dymall.common.util.UserContext;
import com.dymall.user.domain.po.Address;
import com.dymall.user.mapper.AddressMapper;
import com.dymall.user.service.IAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {
    @Override
    @Transactional
    public void addAddress(AddressDTO addressDTO) {
        // 1. 校验参数
        if (addressDTO == null || StringUtils.isBlank(addressDTO.getStreet()) ||
                StringUtils.isBlank(addressDTO.getCity()) || StringUtils.isBlank(addressDTO.getProvince()) ||
                StringUtils.isBlank(addressDTO.getMobile()) || StringUtils.isBlank(addressDTO.getContact())) {
            throw new BadRequestException("地址信息不完整");
        }

        // 2. 创建 Address 实体对象
        Address address = BeanUtils.copyBean(addressDTO, Address.class);

        // 3. 绑定当前用户
        Long userId = UserContext.getUser();
        address.setUserId(userId);

        // 4. 处理默认地址逻辑
        if (addressDTO.getIsDefault() != null && addressDTO.getIsDefault() == 1) {
            // 如果用户指定了默认地址，取消之前的默认地址
            update().set("is_default", 0).eq("user_id", userId).update();
            address.setIsDefault(1);
        } else {
            // 如果用户没有传 isDefault，默认设为 0（非默认）
            address.setIsDefault(0);
        }

        // 5. 保存地址到数据库
        save(address);
    }
}
